﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Security.Authentication;
using System.Threading.Tasks;

namespace MongoDBEmbeddedOperation
{
    public class MongoDbContext
    {
        #region Fields
        /// <summary>
        /// 缓存Mongodb集合
        /// </summary>
        private Dictionary<string, object> _collectionsMongoDb;

        #endregion

        #region Properties
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string ConnectionString { get; }

        /// <summary>
        /// Mongo客户端设置
        /// </summary>
        public MongoClientSettings Settings { get; }

        /// <summary>
        /// 数据库名称
        /// </summary>
        public string DatabaseName { get; }

        /// <summary>
        /// Mongo上下文 
        /// </summary>
        public IMongoDatabase DbContext { get; }
        #endregion

        /// <summary>
        /// MongoDb数据上下文
        /// </summary>
        /// <param name="connectionString">
        /// 连接字符串，如："mongodb://username:password@host:port/[DatabaseName]?ssl=true"
        /// 详情参见：http://www.runoob.com/mongodb/mongodb-connections.html
        /// </param>
        public MongoDbContext(string connectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
                throw new ArgumentException("connectionString 连接字符串不能为空!");

            try
            {
                var mongoUrl = new MongoUrl(connectionString);
                ConnectionString = connectionString;
                Settings = MongoClientSettings.FromUrl(mongoUrl);

                if (string.IsNullOrWhiteSpace(mongoUrl.DatabaseName))
                    throw new ArgumentException("数据库名称不能为空！");

                DatabaseName = mongoUrl.DatabaseName;
                // SSL加密
                if (Settings.UseSsl)
                {
                    Settings.SslSettings = new SslSettings
                    {
                        EnabledSslProtocols = SslProtocols.Tls12
                    };
                }

                var mongoClient = new MongoClient(Settings);
                DbContext = mongoClient.GetDatabase(DatabaseName);
            }
            catch (Exception e)
            {
                // TODO: 记录错误日志
                throw;
            }
        }

        /// <summary>
        /// 异步获取集合
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public async Task<IMongoCollection<TEntity>> GetCollectionAsync<TEntity>() where TEntity : class
        {
            // 集合缓存如果为空，那么创建一个
            if (_collectionsMongoDb == null)
            {
                _collectionsMongoDb = new Dictionary<string, object>();
            }

            // 获取集合名称，使用的标准是在实体类型名后添加Set
            var collectionName = $"{typeof(TEntity).Name}Set";

            // 如果集合不存在，那么创建集合
            if (false == await IsCollectionExistsAsync<TEntity>())
            {
                await DbContext.CreateCollectionAsync(collectionName);
            }

            // 如果缓存中没有该集合，那么加入缓存
            if (!_collectionsMongoDb.ContainsKey(collectionName))
            {
                _collectionsMongoDb[collectionName] = DbContext.GetCollection<TEntity>(collectionName);
            }

            // 从缓存中取出集合返回
            return (IMongoCollection<TEntity>)_collectionsMongoDb[collectionName];
        }

        /// <summary>
        /// 集合是否存在
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public async Task<bool> IsCollectionExistsAsync<TEntity>()
        {
            var filter = new BsonDocument("name", $"{typeof(TEntity).Name}Set");
            // 通过集合名称过滤
            var collections = await DbContext.ListCollectionsAsync(new ListCollectionsOptions { Filter = filter });
            // 检查是否存在
            return await collections.AnyAsync();
        }
    }
}
